package com.example.protestgps;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;






import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class UploadFile extends Activity{
	
	public static final int DIALOG_UPLOAD_PROGRESS = 0;
	private ProgressDialog mProgressDialog;
	GoogleMap myMap;
	private LocationManager lm;
	public double latchange = 0;
	public double lngchange = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.uploadfile);
		// Permission StrictMode
				if (android.os.Build.VERSION.SDK_INT > 9) {
					StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
							.permitAll().build();
					StrictMode.setThreadPolicy(policy);
				}

				      
			        	final EditText txtSDCard = (EditText) findViewById(R.id.txtSDCard);
			        	txtSDCard.setText(getIntent().getStringExtra("Path"));
			        	Button btnUpload = (Button) findViewById(R.id.btnUpload);
			        	
			        	
			        	btnUpload.setOnClickListener(new OnClickListener() {
			    			public void onClick(View v) {
			    				// TODO Auto-generated stub

			    				final String strSDPath = txtSDCard.getText().toString();
			    				final String strUrlServer = "http://192.168.1.101/myexample/uploadFile.php";

			    				new UploadFileAsync().execute(strSDPath, strUrlServer);

			    			}
			    		});
			    	}
			    	
				

	
	
	public void showSuscess(String resServer)
    {
    	
    	String strStatusID = "0";
    	String strError = "Unknow Status!";

    	try {  		
    		
			JSONObject c = new JSONObject(resServer);
        	strStatusID = c.getString("StatusID");
        	strError = c.getString("Error");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	
    	// Prepare Status
		if(strStatusID.equals("0"))
		{
			AlertDialog.Builder ad  = new AlertDialog.Builder(this);
			ad.setTitle("Error!");
			ad.setIcon(android.R.drawable.btn_star_big_on);
            ad.setMessage(strError);
            ad.setPositiveButton("Close", null);
            ad.show();
		}
		else
		{
			Toast.makeText(UploadFile.this, "Upload file Successfully", Toast.LENGTH_SHORT).show();
			Intent gotonext = new Intent(getApplicationContext(),ShowMapandHttpPostVoice.class);
			startActivity(gotonext);		
		
		}
		
    }
	 
	 @Override
	    protected Dialog onCreateDialog(int id) {
	        switch (id) {
	        case DIALOG_UPLOAD_PROGRESS:
	            mProgressDialog = new ProgressDialog(this);
	            mProgressDialog.setMessage("Uploading file.....");
	            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	            mProgressDialog.setCancelable(true);
	            mProgressDialog.show();
	            return mProgressDialog;
	        default:
	            return null;
	        }
	    }
	 
	 
	 public class UploadFileAsync extends AsyncTask<String, Void, Void> {

	    	String resServer;
	    	
	        protected void onPreExecute() {
	        	super.onPreExecute();
	        	showDialog(DIALOG_UPLOAD_PROGRESS);
	        }

	        @Override
	        protected Void doInBackground(String... params) {
	            // TODO Auto-generated method stub

	        	int bytesRead, bytesAvailable, bufferSize;
	    		byte[] buffer;
	    		int maxBufferSize = 1 * 2024 * 2024;
	    		int resCode = 0;
	        	String resMessage = "";

	        	String lineEnd = "\r\n";
	        	String twoHyphens = "--";
	        	String boundary =  "*****";
	        	
	    	    String strSDPath = params[0];
	    	    String strUrlServer = params[1];
	    	    
	    		try {
	    			//** Check file on SD Card ***//*
	    			File file = new File(strSDPath);
	    			if(!file.exists())
	    			{
	    				resServer = "{\"StatusID\":\"0\",\"Error\":\"Please check path on SD Card\"}";
	    				return null;
	    			}
	    			
	    			FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));

	    			URL url = new URL(strUrlServer);
	    			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	    			conn.setDoInput(true);
	    			conn.setDoOutput(true);
	    			conn.setUseCaches(false);
	    			conn.setRequestMethod("POST");

	    			conn.setRequestProperty("Connection", "Keep-Alive");
	    			conn.setRequestProperty("Content-Type",
	    					"multipart/form-data;boundary=" + boundary);

	    			DataOutputStream outputStream = new DataOutputStream(conn
	    					.getOutputStream());
	    			outputStream.writeBytes(twoHyphens + boundary + lineEnd);
	    			outputStream
	    					.writeBytes("Content-Disposition: form-data; name=\"filUpload\";filename=\""
	    							+ strSDPath + "\"" + lineEnd);
	    			outputStream.writeBytes(lineEnd);

	    			bytesAvailable = fileInputStream.available();
	    			bufferSize = Math.min(bytesAvailable, maxBufferSize);
	    			buffer = new byte[bufferSize];

	    			// Read file
	    			bytesRead = fileInputStream.read(buffer, 0, bufferSize);

	    			while (bytesRead > 0) {
	    				outputStream.write(buffer, 0, bufferSize);
	    				bytesAvailable = fileInputStream.available();
	    				bufferSize = Math.min(bytesAvailable, maxBufferSize);
	    				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
	    			}

	    			outputStream.writeBytes(lineEnd);
	    			outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

	    			// Response Code and  Message
	    			resCode = conn.getResponseCode();
	    			if(resCode == HttpURLConnection.HTTP_OK)
	    			{
	                    InputStream is = conn.getInputStream();
	                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
	                    
	                    int read = 0;
	                    while ((read = is.read()) != -1) {
	                          bos.write(read);
	                    }
	                    byte[] result = bos.toByteArray();
	                    bos.close();
	                         
	                    resMessage = new String(result);
	                    
	    			}
	    			
	    			Log.d("resCode=",Integer.toString(resCode));
	    			Log.d("resMessage=",resMessage.toString());

	    			fileInputStream.close();
	    			outputStream.flush();
	    			outputStream.close();
	    			
	    			resServer = resMessage.toString();
	    			
	    			
	    		} catch (Exception ex) {
	    			// Exception handling
	    			return null;
	    		}
	    		
	    		return null;
	        }

	        protected void onPostExecute(Void unused) {
	        	showSuscess(resServer);
	            dismissDialog(DIALOG_UPLOAD_PROGRESS);
	            removeDialog(DIALOG_UPLOAD_PROGRESS);
	        }

	    }
	
	    
	
}
